package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.TbAddress;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.AddressService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.IdWorker;
import com.dongdongshop.vo.CartVO;
import com.dongdongshop.vo.OrderVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("order")
public class OrderController {

    @DubboReference
    private OrderService orderService;

    @RequestMapping("pay")
    public String pay(){
        return "pay";
    }
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("toAddOrder")
    @ResponseBody
    public Result toAddOrder(TbOrder Order){
        //调用order服务进行订单保存
        //拿到返回值，母订单号，以及订单名称等信息
        TbUser tbUser = (TbUser) SecurityUtils.getSubject().getPrincipal();
        String userId = tbUser.getUsername();
        Order.setUserId(userId);
        IdWorker idWorker = new IdWorker();
        String OutTradeNo = idWorker.nextId() + "";
        Order.setOutTradeNo(OutTradeNo);
        OrderVO orderVO = orderService.toAddOrder(Order);
        return Result.ok().setData(orderVO);
    }

    @RequestMapping("selectInfo")
    @ResponseBody
    public Result selectInfo(HttpServletRequest request, Model model){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();

        String tradeNo = (String) redisTemplate.boundValueOps("trade_no").get();
        String outTradeNo = (String) redisTemplate.boundValueOps("out_trade_no").get();
        List<CartVO> cart = orderService.selectInfo(user.getUsername(),outTradeNo,tradeNo);
        return Result.ok().setData(cart);
    }
}
